package org.darkforest.auth;

import org.apache.commons.lang.StringUtils;
import org.darkforest.common.constant.Constants;
import org.darkforest.model.Token;
import org.darkforest.service.TokenService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.web.method.HandlerMethod;
import org.springframework.web.servlet.handler.HandlerInterceptorAdapter;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 * 基于token验证用户是否已登录
 *
 * @auth bingo
 * @create 2017-09-25-14:57
 */
@Component
public class AuthByTokenInterceptor extends HandlerInterceptorAdapter {

    private Logger logger = LoggerFactory.getLogger(AuthByTokenInterceptor.class);

    @Autowired
    private TokenService tokenService;

    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {

        if (handler.getClass().isAssignableFrom(HandlerMethod.class)) {
            AuthPassport authPassport = ((HandlerMethod) handler).getMethodAnnotation(AuthPassport.class);
            if (authPassport == null || authPassport.isLogin() == true) {
                return true;
            } else {
                String xAuthToken = request.getHeader("x-auth-token");
                logger.debug("用户token=======" + xAuthToken);
                if (StringUtils.isBlank(xAuthToken)) {
                    response.setStatus(HttpServletResponse.SC_UNAUTHORIZED);
                    return false;
                } else {
                    Token token = tokenService.getToken(xAuthToken);
                    if (token != null && tokenService.checkToken(token)) {
                        request.setAttribute(Constants.CURRENT_MEMBER_ID, token.getMemberId());
                        return true;
                    } else {
                        response.setStatus(HttpServletResponse.SC_UNAUTHORIZED);
                        return false;
                    }
                }
            }
        }else{
            return true;
        }
    }
}
